<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <input type="text" id="context">
    <button onclick="send()" >发送</button>
<script>
     var interval=self.setInterval("clock()",6000);
    var socket;
    var user= JSON.stringify({
          id: "1234",
         // 连接成功将，用户ID传给服务端
         content: "sdag"
     })
    // 判断当前浏览器是否支持webSocket
    if(window.WebSocket){
        // socket = new WebSocket("ws://124.223.89.220:58080/webSocket")
        socket = new WebSocket("ws://localhost:58080/webSocket")
        // 相当于channel的read事件，ev 收到服务器回送的消息
        socket.onmessage = function (ev) {
            console.log("返回"+ev.data)
            var rt = document.getElementById("responseText");
            rt.value = rt.value + "\n" + ev.data;
        }
        // 相当于连接开启
        socket.onopen = function (ev) {
            var rt = document.getElementById("responseText");
            rt.value =  "连接开启了..."
            socket.send(
                JSON.stringify({
                    status: 1,
                    // 连接成功将，用户ID传给服务端
                    content: user
                })
            );
        }
        // 相当于连接关闭
        socket.onclose = function (ev) {
            var rt = document.getElementById("responseText");
            rt.value = rt.value + "\n" + "连接关闭了...";
           window.clearInterval(interval)
        }
    }else{
        alert("当前浏览器不支持webSocket")
    }


    function clock()
    {
        socket.send(
                JSON.stringify({
                    // 连接成功将，用户ID传给服务端
                    status: "001"
                })
            );
    }

    function send(){
        var rt = document.getElementById("context").value;
        var content= JSON.stringify({
            userId:"1234",
            targetId:"123456",
            magContent: rt
        })
        console.log(rt)
         socket.send(
                JSON.stringify({
                    // 连接成功将，用户ID传给服务端
                   status: "2",
                   content: content
                })
            );
    }


</script>
    <form onsubmit="return false">
        <textarea id="responseText" style="height: 150px; width: 300px;"></textarea>
        <input type="button" value="清空内容" onclick="document.getElementById('responseText').value=''">
    </form>
</body>
</html>